package pfq.demo.designpattern.chainofresponsibilitypattern.activity;

public class ViewGroup extends View {

    ViewGroup(String name) {
        super(name);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        System.out.println(name + ": dispatchTouchEvent");
        // 调用拦截方法
        boolean intercept = onInterceptTouchEvent(event);

        // true：拦截，进入自己的onTouchEvent()方法
        if (intercept) {
            return onTouchEvent(event);
        }

        // false：不拦截，继续向下分发事件
        if (childView.dispatchTouchEvent(event)) {
            return true;
        }

        // 如果子View的dispatchTouchEvent()方法返回false，表示子View不想分发事件，那事件会传到自己的onTouchEvent()方法
        return onTouchEvent(event);
    }

    public boolean onInterceptTouchEvent(MotionEvent event) {
        System.out.println(name + ": onInterceptTouchEvent");
        // 默认不拦截
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    private View childView;

    /**
     * 添加一个子控件
     */
    public void addView(View view) {
        childView = view;
    }


    /**
     * 模拟点击事件
     */
    public void click() {
        // 分发事件
        MotionEvent motionEvent = new MotionEvent();
        dispatchTouchEvent(motionEvent);
    }
}
